CODE 8. Valid Palindrome

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/12/2013-09-12-CODE 8 Valid Palindrome/

访问原文「CODE 8. Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"isnota palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public boolean isPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == s) {
return false;
}
if (s.length() <= 1) {
return true;
}
int i = 0;
int j = s.length() - 1;
while (i < j) {
char a = s.charAt(i);
char b = s.charAt(j);
if (a < '0' || (a > '9' && a < 'A') || (a > 'Z' && a < 'a')
|| a > 'z') {
i++;
continue;
}
if (b < '0' || (b > '9' && b < 'A') || (b > 'Z' && b < 'a')
|| b > 'z') {
j--;
continue;
}
if (a == b || ((a < b) && (a + 32 == b))
|| ((a > b) && (a - 32 == b))) {
i++;
j--;
} else {
break;
}
}
if (i < j) {
return false;
} else {
return true;
}
}
Jerky Lu wechat
欢迎加入微信公众号